<template>
  <div class="app-container problem-management">
    <!-- 搜索区域 -->
    <div class="search-box">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
        <el-form-item label="题目ID" prop="id">
          <el-input v-model="queryParams.id" placeholder="请输入题目ID" class="custom-input" clearable
            suffix-icon="el-icon-search" />
        </el-form-item>
        <el-form-item label="题目标题" prop="title">
          <el-input v-model="queryParams.title" placeholder="请输入题目标题" class="custom-input" clearable
            suffix-icon="el-icon-document" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="queryParams.tags" placeholder="请输入标签" class="custom-input" clearable
            suffix-icon="el-icon-collection-tag" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
            class="action-btn">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="action-btn">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮组 -->
    <div class="action-bar">
      <el-button-group>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" class="gradient-btn"
          v-hasPermi="['problem:problem:add']">新增</el-button>
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" class="gradient-btn"
          v-hasPermi="['problem:problem:edit']">修改</el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" class="gradient-btn"
          v-hasPermi="['problem:problem:remove']">删除</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" class="gradient-btn"
          @click="handleExport">导出</el-button>
      </el-button-group>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" class="right-toolbar" />
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="problemList" @selection-change="handleSelectionChange" class="custom-table"
      stripe header-row-class-name="table-header">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="题目ID" align="center" prop="id" width="100" />
      <el-table-column label="题目标题" align="center" width="220">
        <template slot-scope="scope">
          <router-link :to="`/problem/detail/${scope.row.id}`" class="title-link">
            {{ scope.row.title }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="题目描述" align="center" prop="description" show-overflow-tooltip />
      <el-table-column label="难度" align="center" width="120">
        <template slot-scope="scope">
          <el-tag :type="getDifficultyTag(scope.row.difficulty)" effect="light" class="difficulty-tag">
            {{ scope.row.difficulty }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" width="180">
        <template slot-scope="scope">
          <el-tag v-for="(tag, index) in safeTags(scope.row.tags)" :key="index" type="success" size="mini"
            class="tag-item">
            {{ tag }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button type="text" icon="el-icon-edit" circle @click="handleUpdate(scope.row)"
              class="action-icon edit-icon" />
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button type="text" icon="el-icon-delete" circle @click="handleDelete(scope.row)"
              class="action-icon delete-icon" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" class="custom-pagination" />

    <!-- 新建/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" class="custom-dialog" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="题目标题:" prop="title">
              <el-input v-model="form.title" placeholder="请输入题目标题" class="dialog-input" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度级别:" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="请选择难度" class="dialog-select">
                <el-option label="简单" value="easy" />
                <el-option label="中等" value="medium" />
                <el-option label="困难" value="hard" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="题目描述:" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入详细描述"
            class="dialog-textarea" />
        </el-form-item>

        <el-form-item label="题目标签:" prop="tags">
          <el-select v-model="form.tags" multiple filterable allow-create placeholder="请输入或选择标签"
            class="full-width-select">
            <el-option v-for="item in presetTags" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-divider content-position="left"><i class="el-icon-s-operation" /> 测试用例管理</el-divider>

        <div class="testcase-actions">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddTestCase"
            class="testcase-btn">添加用例</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteTestCase"
            class="testcase-btn">批量删除</el-button>
        </div>

        <el-table :data="testCaseList" border class="testcase-table" @selection-change="handleTestCaseSelectionChange">
          <el-table-column type="selection" width="45" align="center" />
          <el-table-column label="序号" width="60" align="center">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="输入数据" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.input" type="textarea" :rows="2" placeholder="输入测试数据"
                class="testcase-input" />
            </template>
          </el-table-column>
          <el-table-column label="期望输出" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.output" type="textarea" :rows="2" placeholder="输入预期输出"
                class="testcase-output" />
            </template>
          </el-table-column>
          <el-table-column label="是否公开" width="120" align="center">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.isPublic" true-label="1" false-label="0">
                {{ scope.row.isPublic === '1' ? '公开' : '隐藏' }}
              </el-checkbox>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" class="dialog-btn">取 消</el-button>
        <el-button type="primary" @click="submitForm" class="dialog-btn confirm-btn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProblem, getProblem, delProblem, addProblem, updateProblem } from "@/api/problem/problem";

export default {
  name: "Problem",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTestCase: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目管理表格数据
      problemList: [],
      // 测试用例表格数据
      testCaseList: [],
      // 预设标签
      presetTags: ['数组', '字符串', '动态规划', '树', '图论'],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        title: null,
        description: null,
        difficulty: null,
        tags: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "题目标题不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询题目管理列表 */
    getList() {
      this.loading = true;
      listProblem(this.queryParams).then(response => {
        this.problemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 安全解析标签
    safeTags(tags) {
      try {
        return tags ? tags.split(',') : []
      } catch {
        return []
      }
    },

    // 获取难度标签样式
    getDifficultyTag(difficulty) {
      const map = {
        easy: 'success',
        medium: 'warning',
        hard: 'danger'
      }
      return map[difficulty?.toLowerCase()] || 'info'
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        description: null,
        difficulty: null,
        tags: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.testCaseList = [];
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题目";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getProblem(id).then(response => {
        this.form = {
          ...response.data,
          tags: response.data.tags ? response.data.tags.split(',') : [] // 字符串转数组
        };
        this.testCaseList = response.data.testCaseList || [];
        this.open = true;
        this.title = "修改题目";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 转换tags为逗号分隔字符串
          const postData = {
            ...this.form,
            tags: this.form.tags.join(','), // 数组转字符串
            testCaseList: this.testCaseList
          };

          if (postData.id != null) {
            updateProblem(postData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProblem(postData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除题目管理编号为"' + ids + '"的数据项？').then(() => {
        return delProblem(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    /** 测试用例添加按钮操作 */
    handleAddTestCase() {
      this.testCaseList.push({
        input: "",
        output: "",
        isPublic: "0" // 默认设置为不公开
      });
    },

    /** 测试用例删除按钮操作 */
    handleDeleteTestCase() {
      if (this.checkedTestCase.length === 0) {
        this.$modal.msgError("请先选择要删除的测试用例数据");
      } else {
        this.testCaseList = this.testCaseList.filter((item, index) =>
          !this.checkedTestCase.includes(index)
        );
        this.checkedTestCase = [];
      }
    },

    /** 复选框选中数据 */
    handleTestCaseSelectionChange(selection) {
      this.checkedTestCase = selection.map((item, index) => index);
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('problem/problem/export', {
        ...this.queryParams
      }, `problem_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  background: #ffffff;
  padding: 20px;
  border-radius: 4px;

  .search-box {
    background: transparent;
    padding: 0;
    margin-bottom: 16px;

    .el-form-item {
      margin-bottom: 12px;
      margin-right: 16px;
    }

    .custom-input {
      width: 240px;

      &::v-deep .el-input__inner {
        border-radius: 4px;
        background: #f8f9fa;
        border: 1px solid #e4e7ed;
      }
    }

    .action-btn {
      margin-left: 8px;
      border-radius: 4px;
      padding: 7px 16px;
    }
  }

  .action-bar {
    margin: 16px 0;

    .gradient-btn {
      background: #409EFF;
      border-radius: 4px;
      padding: 7px 16px;
      transition: all 0.2s;

      &+.gradient-btn {
        margin-left: 8px;
      }

      &:hover {
        opacity: 0.9;
      }
    }
  }

  .custom-table {
    border: 1px solid #e4e7ed;

    &::v-deep .table-header {
      background: #f8f9fa;

      th {
        color: #606266;
        font-weight: 500;
      }
    }

    .title-tag {
      font-size: 14px;
      color: #409EFF;
      background: rgba(64, 158, 255, 0.1);
      padding: 4px 8px;
      border-radius: 4px;
    }

    .title-link {
      color: #409EFF;
      text-decoration: none;
      font-weight: 500;
      transition: color 0.2s;

      &:hover {
        color: #337ecc;
        text-decoration: underline;
      }
    }

    /* 移除标签背景 */
    ::v-deep .el-tag {
      background: none !important;
      border: none !important;
      padding: 0 !important;
    }

    .difficulty-tag {
      font-weight: 500;
      border: none;

      &.easy {
        color: #67C23A;
        background: rgba(103, 194, 58, 0.1);
      }

      &.medium {
        color: #E6A23C;
        background: rgba(230, 162, 60, 0.1);
      }

      &.hard {
        color: #F56C6C;
        background: rgba(245, 108, 108, 0.1);
      }
    }

    .tag-item {
      background: #f0f2f5;
      color: #606266;
      border: none;
      margin: 2px 4px;
      border-radius: 3px;
    }

    .action-icon {
      color: #909399;

      &.edit-icon:hover {
        color: #409EFF;
      }

      &.delete-icon:hover {
        color: #F56C6C;
      }
    }
  }

  .custom-pagination {
    margin-top: 16px;
  }

  .custom-dialog {
    &::v-deep .el-dialog {
      border-radius: 8px;

      .el-dialog__header {
        padding: 16px 24px;
        border-bottom: 1px solid #e4e7ed;

        .el-dialog__title {
          color: #303133;
          font-weight: 500;
        }
      }
    }

    .dialog-input,
    .dialog-select,
    .dialog-tags {
      &::v-deep .el-input__inner {
        border-radius: 4px;
      }
    }

    .testcase-table {
      border: 1px solid #e4e7ed;

      &::v-deep .el-checkbox__inner {
        border-color: #dcdfe6;
      }
    }

    .dialog-footer {
      padding: 16px 24px;
      border-top: 1px solid #e4e7ed;

      .dialog-btn {
        border-radius: 4px;
        padding: 8px 20px;

        &.confirm-btn {
          background: #409EFF;
          border-color: #409EFF;
        }
      }
    }
  }
}

/* 统一输入项宽度 */
::v-deep {

  .el-input,
  .el-select,
  .el-textarea {
    width: 100%;
  }

  /* 标签选择器优化 */
  .full-width-select {
    width: 100%;

    .el-select__tags {
      max-width: calc(100% - 40px);
      flex-wrap: wrap;
    }

    .el-select__input {
      min-width: 120px;
    }
  }
}

/* 调整弹窗表单布局 */
.custom-dialog {
  ::v-deep .el-form-item__content {
    width: calc(100% - 100px);
  }
}
</style>